<?php

###########################################################################
#   Copyright (C) 2012 CDNPAL LTD by Christopher Gu                       #
#   resources@cdnpal.com                                                  #
#                                                                         #
#   coded for Php 4.3/5.X and above                                       #
#   and AllowOverride all for .htaccess                                   #
#                                                                         #
#   This program is free software released                                #
#   under the GPL version 2 license:                                      #
#   http://www.gnu.org/licenses/gpl-2.0.htm                               #
#                                                                         #
#   This program is distributed WITHOUT ANY WARRANTY                      #
#   or FITNESS FOR A PARTICULAR PURPOSE.                                  #
#                                                                         #
#   DADF-SDK                                                              #
#                                                                         #
###########################################################################

class IncomingRequestTransformer extends IncomingTransformer {
	
	private $table_direction = 'Incoming';
	
	public $bid_request_id;
	
	public function __construct($request_xml, $schema_filename, $table_direction = 'Incoming') {
		
		$this->table_direction = $table_direction;
		
		$xmlservice = new XMLService($request_xml, $schema_filename);

		$class_name = $this->table_direction .  'BidRequest';
		$bid_request = new $class_name();
		$column_name = $this->table_direction . 'RequestPartnerID';
		$bid_request->$column_name = 0;
		$bid_request->save();

		$class_name 							= $this->table_direction .  'BidRequestHost';
		$bid_request_host 						= new $class_name();
		$column_name 							= $this->table_direction . 'BidRequestID';
		$bid_request_host->$column_name			= $bid_request->$column_name;
		if ($table_direction == 'Incoming'):
			$bid_request_host->RemoteHostAddr	= isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ""; 
		else:
			$bid_request_host->RemoteURL		= isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ""; 
		endif;
		
		$bid_request_host->HttpResponseCode		= 400;
		$bid_request_host->save();
		
		$column_name 			= $this->table_direction . 'BidRequestID';
		$this->bid_request_id 	= $bid_request->$column_name;
		
		$request_authentication = null;
		$using_partner_authentication = Zend_Registry::get('partner.authentication');
		
		if (count($xmlservice->doc->getElementsByTagName('authentication'))
				&& $xmlservice->doc->getElementsByTagName('authentication')->item(0) !== null):
				
			$authentication 				= $xmlservice->doc->getElementsByTagName('authentication')->item(0);					
			$username 						= $xmlservice->get_single_child($authentication, 'username');
			$password 						= $xmlservice->get_single_child($authentication, 'password');
			
			$class_name 					= $this->table_direction .  'RequestAuthentication';
			$request_authentication 		= new $class_name();
			$column_name 					= $this->table_direction . 'BidRequestID';
			$request_authentication->$column_name 			= $bid_request->$column_name;
			$request_authentication->Username 				= $username;
			if ($table_direction == 'Incoming'):
				$request_authentication->PasswordMD5 		= md5($password);
			else:
				$request_authentication->PasswordEncoded 	= EncryptUtils::encrypt_pass($password);
			endif;
			$request_authentication->save();
			
		endif;

		$adbundle_list = $xmlservice->get_node_children($xmlservice->doc, 'adbundle');
		
		foreach ($adbundle_list as $adbundle):
		
			$requestdate 						= $xmlservice->get_single_child($authentication, 'requestdate');
		
			$class_name 						= $this->table_direction .  'RequestAdbundle';
			$request_adbundle 					= new $class_name();
			$column_name 						= $this->table_direction . 'BidRequestID';
			$request_adbundle->$column_name 	= $bid_request->$column_name;
			$request_adbundle->RequestDate 		= TimeUtils::xml_date_to_mysql_date($requestdate);
			$request_adbundle->save();

			// advertisement
			
			$advertisement_list = $xmlservice->get_node_children($adbundle, 'advertisement'); 
			
			foreach ($advertisement_list as $advertisement):
				
				$ad_quality 			= $xmlservice->get_single_child($advertisement, 'adquality');
				$cpm 					= $xmlservice->get_single_child($advertisement, 'cpm');
				$cpc 					= $xmlservice->get_single_child($advertisement, 'cpc');
				$cpa 					= $xmlservice->get_single_child($advertisement, 'cpa');
				$maximpressions 		= $xmlservice->get_single_child($advertisement, 'maximpressions');
				$maxclicks 				= $xmlservice->get_single_child($advertisement, 'maxclicks');
				$maxpayout 				= $xmlservice->get_single_child($advertisement, 'maxpayout');
				$ournumbers 			= $xmlservice->get_single_child($advertisement, 'ournumbers');
				$id 					= $xmlservice->get_single_child($advertisement, 'id');
				$name 					= $xmlservice->get_single_child($advertisement, 'name');
				$description 			= $xmlservice->get_single_child($advertisement, 'description');
				$flightdatestart 		= $xmlservice->get_single_child($advertisement, 'flightdatestart');
				$flightdatefinish 		= $xmlservice->get_single_child($advertisement, 'flightdatefinish');
				$netpayabledelaydays 	= $xmlservice->get_single_child($advertisement, 'netpayabledelaydays');
				$pausetrigger 			= $xmlservice->get_single_child($advertisement, 'pausetrigger');
				$resumetrigger 			= $xmlservice->get_single_child($advertisement, 'resumetrigger');
			
				$class_name 					= $this->table_direction .  'RequestAdvertisement';
				$request_advertisement = new $class_name();
				$column_name 					= $this->table_direction . 'RequestAdbundleID';
				$request_advertisement->$column_name					= $request_adbundle->$column_name;
				if ($ad_quality !== null):
					$request_advertisement->AdQuality 					= $ad_quality;
				endif;
				if ($cpm !== null):
					$request_advertisement->CPM							= $cpm;
				endif;
				if ($cpc !== null):
					$request_advertisement->CPC							= $cpc;
				endif;
				if ($cpa !== null):
					$request_advertisement->CPA							= $cpa;
				endif;
				$request_advertisement->MaxImpressions					= $maximpressions === null ? 0 : $maximpressions;
				$request_advertisement->MaxClicks						= $maxclicks === null ? 0 : $maxclicks;
				$request_advertisement->MaxPayout						= $maxpayout === null ? 0 : $maxpayout;
				
				if ($ournumbers !== null):
					$request_advertisement->OurNumbers					= $this->from_boolean($ournumbers);
				endif;
					
				$request_advertisement->ID							= $id === null ? 0 : $id;
				$request_advertisement->Name						= $name === null ? "" : $name;
				$request_advertisement->Description					= $description === null ? "" : $description;
				$request_advertisement->FlightDateStart				= TimeUtils::xml_date_to_mysql_date($flightdatestart);
				$request_advertisement->FlightDateFinish			= TimeUtils::xml_date_to_mysql_date($flightdatefinish);
				$request_advertisement->NetPayableDelayDays			= $netpayabledelaydays ? 0 : $netpayabledelaydays;
				
				if ($pausetrigger !== null):
					$request_advertisement->PauseTrigger			= $pausetrigger;
				endif;
				
				if ($resumetrigger !== null):
					$request_advertisement->ResumeTrigger			= $resumetrigger;
				endif;

				$request_advertisement->save();
				
				if (count($advertisement->getElementsByTagName('code'))
						&& $advertisement->getElementsByTagName('code')->item(0) !== null):
				
					$code_size_list = $xmlservice->get_node_children($advertisement->getElementsByTagName('code')->item(0), 'size'); 
				else:
					throw new Exception("No advertisement code tag found");	
				endif;
				
				foreach ($code_size_list as $code_size):
					
					$name 				= $code_size->getAttribute('name');
					$height 			= $code_size->getAttribute('height');
					$width 				= $code_size->getAttribute('width');
					$iframe 			= $xmlservice->get_single_child($code_size, 'iframe');
					$javascript 		= $xmlservice->get_single_child($code_size, 'javascript');
					
					$class_name 						= $this->table_direction .  'RequestCodeSize';
					$request_code_size 		= new $class_name();
					$column_name 						= $this->table_direction . 'RequestAdvertisementID';
					$request_code_size->$column_name 	= $request_advertisement->$column_name;
					$request_code_size->Name 			= $name;
					$request_code_size->Height			= $height;
					$request_code_size->Width			= $width;
					$request_code_size->IFrame			= $iframe;
					$request_code_size->Javascript		= $javascript;
					$request_code_size->save();
					
					$rotation_list = $xmlservice->get_node_children($code_size, 'rotation'); 
					
					if (count($rotation_list) && $rotation_list->item(0) !== null):
						
						$rotation 			= $rotation_list->item(0);
						$numerator 			= $xmlservice->get_single_child($rotation, 'numerator');
						$denominator 		= $xmlservice->get_single_child($rotation, 'denominator');
						
						$class_name 						= $this->table_direction .  'RequestCodeSizeRotation';
						$request_rotation 					= new $class_name();
						$column_name 						= $this->table_direction . 'RequestCodeSizeID';
						$request_rotation->$column_name 	= $request_code_size->$column_name;
						$request_rotation->Numerator 		= $numerator;
						$request_rotation->Denominator 		= $denominator;
						$request_rotation->save();
						
					endif;

				// end code
				endforeach;
							
				if (count($advertisement->getElementsByTagName('filter'))
							&& $advertisement->getElementsByTagName('filter')->item(0) !== null):
				
					$filter 				= $advertisement->getElementsByTagName('filter')->item(0); 
					
					$proxies 				= $xmlservice->get_single_child($filter, 'proxies');
					$ismobile 				= $xmlservice->get_single_child($filter, 'ismobile');
					$istablet 				= $xmlservice->get_single_child($filter, 'istablet');
					$isbrandsafe 			= $xmlservice->get_single_child($filter, 'isbrandsafe');
					$isporn 				= $xmlservice->get_single_child($filter, 'isporn');
					$iscpa 					= $xmlservice->get_single_child($filter, 'iscpa');
					$isabovethefold 		= $xmlservice->get_single_child($filter, 'isabovethefold');
					$category 				= $xmlservice->get_single_child($filter, 'category');
					$subcategory 			= $xmlservice->get_single_child($filter, 'subcategory');

					$class_name				= $this->table_direction .  'RequestFilter';
					$request_filter 		= new $class_name();
					$column_name 			= $this->table_direction . 'RequestAdvertisementID';
					$request_filter->$column_name		= $request_advertisement->$column_name;
					$request_filter->Proxies 			= $this->from_boolean($proxies);
					$request_filter->IsMobile 			= $this->from_boolean($ismobile);
					$request_filter->IsTablet 			= $this->from_boolean($istablet);
					$request_filter->IsBrandSafe 		= $this->from_boolean($isbrandsafe);
					$request_filter->IsPorn 			= $this->from_boolean($isporn);
					$request_filter->IsCPA 				= $this->from_boolean($iscpa);
					$request_filter->IsAboveTheFold 	= $this->from_boolean($isabovethefold);
					$request_filter->Category 			= $category;
					$request_filter->SubCategory 		= $subcategory;
					$request_filter->save();
					
					
					if (count($advertisement->getElementsByTagName('geo'))
								&& $advertisement->getElementsByTagName('geo')->item(0) !== null):
					
						$filter_geo_countries_list = $xmlservice->get_node_children($advertisement->getElementsByTagName('geo')->item(0), 'countries'); 
		
						if (count($filter_geo_countries_list)
									&& $filter_geo_countries_list->item(0) !== null):
						
							$filter_geo_country_list = $xmlservice->get_node_children($filter_geo_countries_list->item(0), 'country');
								
							foreach ($filter_geo_country_list as $filter_geo_country):
								
								$class_name 								= $this->table_direction .  'RequestFilterGeoCountry';
								$request_filter_geo_country 				= new $class_name();
								$column_name 								= $this->table_direction . 'RequestFilterID';
								$request_filter_geo_country->$column_name 	= $request_filter->$column_name;
								$request_filter_geo_country->CountryCode 	= $filter_geo_country->nodeValue;
								$request_filter_geo_country->save();
								
							endforeach;
							
						endif;
						
						$filter_geo_states_list = $xmlservice->get_node_children($advertisement->getElementsByTagName('geo')->item(0), 'states');
						
						if (count($filter_geo_states_list)
									&& $filter_geo_states_list->item(0) !== null):
							
							$filter_geo_state_list = $xmlservice->get_node_children($filter_geo_states_list->item(0), 'state');
							
							foreach ($filter_geo_state_list as $filter_geo_state):
								
								$class_name 								= $this->table_direction .  'RequestFilterGeoState';
								$request_filter_geo_state 					= new $class_name();
								$column_name 								= $this->table_direction . 'RequestFilterID';
								$request_filter_geo_state->$column_name 	= $request_filter->$column_name;
								$request_filter_geo_state->State		 	= $filter_geo_state->nodeValue;
								$request_filter_geo_state->save();
								
							endforeach;
							
						endif;
						
					// end geo
					endif;

					if (count($advertisement->getElementsByTagName('languages'))
								&& $advertisement->getElementsByTagName('languages')->item(0) !== null):
					
						$filter_language_list = $xmlservice->get_node_children($advertisement->getElementsByTagName('languages')->item(0), 'language');
										
						foreach ($filter_language_list as $filter_language):
										
							$class_name 							= $this->table_direction .  'RequestFilterLanguage';
							$request_filter_language 				= new $class_name();
							$column_name 							= $this->table_direction . 'RequestFilterID';
							$request_filter_language->$column_name 	= $request_filter->$column_name;
							$request_filter_language->LanguageCode 	= $filter_language->nodeValue;
							$request_filter_language->save();
										
						endforeach;
									
					endif;
					
				// end filter
				endif;
				
					
				if (count($advertisement->getElementsByTagName('famousbrands'))):
				
					$brand_list = $xmlservice->get_node_children($advertisement->getElementsByTagName('famousbrands')->item(0), 'brand');
										
					foreach ($brand_list as $brand):
										
						$class_name 							= $this->table_direction .  'RequestFamousBrand';
						$request_famous_brand 					= new $class_name();
						$column_name 							= $this->table_direction . 'RequestAdvertisementID';
						$request_famous_brand->$column_name 	= $request_advertisement->$column_name;
						$request_famous_brand->BrandName 		= $brand->nodeValue;
						$request_famous_brand->save();
									
					endforeach;

				// famous brands
				endif;
				
				
			// end advertisement
			endforeach;
			
			
			// customers
			
			if (count($adbundle->getElementsByTagName('customers'))
					&& $adbundle->getElementsByTagName('customers')->item(0) !== null):
					
				$customer_list = $xmlservice->get_node_children($adbundle->getElementsByTagName('customers')->item(0), 'customer');

				foreach ($customer_list as $customer):
	
					if (count($customer->getElementsByTagName('contact'))):
					
						$contact_list = $xmlservice->get_node_children($customer, 'contact');
											
						foreach ($contact_list as $contact):
	
							$firstname 				= $xmlservice->get_single_child($contact, 'firstname');
							$lastname 				= $xmlservice->get_single_child($contact, 'lastname');
							$phone 					= $xmlservice->get_single_child($contact, 'phone');
							$email 					= $xmlservice->get_single_child($contact, 'email');
						
							$class_name 								= $this->table_direction .  'RequestCustomerContact';
							$request_customer_contact 					= new $class_name();
							$column_name 								= $this->table_direction . 'RequestAdbundleID';
							$request_customer_contact->$column_name 	= $request_adbundle->$column_name;
							$request_customer_contact->FirstName		= $firstname;
							$request_customer_contact->LastName			= $lastname;
							$request_customer_contact->Phone			= $phone;
							$request_customer_contact->FirstName		= $firstname;
							$request_customer_contact->save();
							
						endforeach;
	
					// famous brands
					endif;
	
				endforeach;
				
			endif;	
			
			// vendor
			
			if (count($adbundle->getElementsByTagName('vendor'))
						&& $adbundle->getElementsByTagName('vendor')->item(0) !== null):
					
				$vendor = $adbundle->getElementsByTagName('vendor')->item(0);
			
				if (count($vendor->getElementsByTagName('contact'))
							&& $vendor->getElementsByTagName('contact')->item(0) !== null):
					
					$contact = $vendor->getElementsByTagName('contact')->item(0);

					$firstname 				= $xmlservice->get_single_child($contact, 'firstname');
					$lastname 				= $xmlservice->get_single_child($contact, 'lastname');
					$phone 					= $xmlservice->get_single_child($contact, 'phone');
					$email 					= $xmlservice->get_single_child($contact, 'email');

					$class_name 							= $this->table_direction .  'RequestVendorContact';
					$request_vendor_contact 				= new $class_name();
					$column_name 							= $this->table_direction . 'RequestAdbundleID';
					$request_vendor_contact->$column_name 	= $request_adbundle->$column_name;
					$request_vendor_contact->FirstName 		= $firstname;
					$request_vendor_contact->LastName 		= $lastname;
					$request_vendor_contact->Phone		 	= $phone;
					$request_vendor_contact->Email		 	= $email;
					$request_vendor_contact->save();
					
					
				endif;
				
				$partnerid 					= $xmlservice->get_single_child($vendor, 'partnerid');
				$partnername 				= $xmlservice->get_single_child($vendor, 'partnername');
				
				if ($using_partner_authentication == true && $table_direction == 'Incoming'):
					
					if ($request_authentication === null 
							|| PartnerAuthentication::is_valid_user_for_partner_id($partnerid, 
															$request_authentication->Username, 
															$request_authentication->PasswordMD5)
															== false):

						throw new Exception("PartnerID is invalid for the username and password provided");
															
					endif;
				endif;
				
				$class_name 							= $this->table_direction .  'RequestVendorPartner';
				$request_vendor_partner 				= new $class_name();
				$column_name 							= $this->table_direction . 'RequestAdbundleID';
				$request_vendor_partner->$column_name 	= $request_adbundle->$column_name;
				$request_vendor_partner->PartnerID 		= $partnerid;
				$request_vendor_partner->PartnerName 	= $partnername;
				$request_vendor_partner->save();
				

			endif;
		
		endforeach;

		$bid_request_host->HttpResponseCode		= 200;
		$bid_request_host->save();
		
	}

};

